/**
 * 
 */
package dh.abs.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import dh.abs.Suspendable;
import dh.abs.info.IllegalParameterException;

/**
 * Logger of simulation
 * @author denialhumanity
 *
 */
public class SimulationLogger {

	/** list of instances implementing Suspendable interface */
	private List<Suspendable> loggingList;
	
	/** path of directory that stores log files */
	private String prefix = ".";
	
	/**
	 * Default constructor.
	 */
	public SimulationLogger() {
		loggingList = new ArrayList<Suspendable>();
	}
	
	/**
	 * add suspendable instance to log it.
	 * @param obj
	 */
	public void addObject(Suspendable obj) {
		loggingList.add(obj);
	}
	
	/**
	 * set path of directory.
	 * @param path
	 * @throws IllegalParameterException
	 */
	public void setPrefix(String path) throws IllegalParameterException {
		prefix = path;
		File file = new File(prefix);
		if(file.exists()) {
			if(!file.isDirectory()) {
				throw new IllegalParameterException("parameter prefix is invalid");
			}
		} else {
			file.mkdirs();
		}
	}
	
	/**
	 * This method logs all the instances in loggingList field.
	 */
	public void logging() {
		for(Suspendable obj: loggingList) {
			File file = new File(prefix + File.separator + obj.getClass().getName() + "-" +obj.getID() + ".log");
			
			BufferedWriter bw = null;
			
			try {
				bw = new BufferedWriter(new FileWriter(file, true));
				
				bw.write(obj.toString());
				bw.newLine();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if(bw != null) {
					try {
						bw.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
